/*******************************************************************************
 *  Copyright (c) 2020-2201 Yichen Science and Tecthnology Co., Ltd.
 *
 *  File   :    debuglog.c
 *  Author :    luomin
 *  E_mail :    luomin5417@qq.com
 *  Date   :    2021/10/28
 *  Desc   :    debug log information to log files and print the info to terminal.   
 *
 *  History:
 *  Date                      Modifier                    Content
******************************************************************************/
#include <stdint.h>

#include "debuglog.h"

extern int g_debuglevel;
extern FILE *g_logstream;

uint8_t g_level_name[][16] = {
    "all",
    "debug",
    "info",
    "warning",
    "error",
    "fatal",
    "off"
};

void debug_log(int level, const char *func, int lines, char *fmt, ...)
{
    char buf[256] = {0};

    if (level >= g_debuglevel)
    {
        fprintf(stdout, "%s %s():%d:%s: ", __TIME__, func, lines, g_level_name[level]); 
        if (g_logstream != NULL)
        {
            fprintf(g_logstream, "%s %s():%d:%s: ", __TIME__, func, lines, g_level_name[level]); 
        }

        va_list valist;
        va_start(valist, fmt);
        vsprintf(buf, fmt, valist);
        va_end(valist);
        
        fprintf(stdout, "%s", buf);
        if (g_logstream != NULL)
        {
            fprintf(g_logstream,"%s", buf);
        }

        fprintf(stdout,"\n");
        if (g_logstream != NULL)
        {
            fprintf(g_logstream, "\n");
        }

        fflush(stdout);
        if (g_logstream != NULL)
        {
            fflush(g_logstream);
        }
    }
}